<?php

if (!function_exists("get_include_contents")) {

    function get_include_contents($filename, $data='') {
        if (is_file($filename)) {
            if (is_array($data)) {
                extract($data);
            }
            ob_start();
            include $filename;
            $contents = ob_get_contents();
            ob_end_clean();
            return $contents;
        }
        return false;
    }

}
if (!function_exists("add_include_path")) {

    function add_include_path($path) {
        foreach (func_get_args () AS $path) {
            if (!file_exists($path) OR (file_exists($path) && filetype($path) !== 'dir')) {
                trigger_error("Include path '{$path}' not exists", E_USER_WARNING);
                continue;
            }

            $paths = explode(PATH_SEPARATOR, get_include_path());

            if (array_search($path, $paths) === false)
                array_push($paths, $path);

            set_include_path(implode(PATH_SEPARATOR, $paths));
        }
    }

}
if (!function_exists("remove_include_path")) {

    function remove_include_path($path) {
        foreach (func_get_args () AS $path) {
            $paths = explode(PATH_SEPARATOR, get_include_path());

            if (($k = array_search($path, $paths)) !== false)
                unset($paths[$k]);
            else
                continue;

            if (!count($paths)) {
                trigger_error("Include path '{$path}' can not be removed because it is the only", E_USER_NOTICE);
                continue;
            }

            set_include_path(implode(PATH_SEPARATOR, $paths));
        }
    }

}

if (!function_exists('get_called_class')) {

    class class_tools {

        static $i = 0;
        static $fl = null;

        static function get_called_class() {
            $bt = debug_backtrace();

            if (self::$fl == $bt[2]['file'] . $bt[2]['line']) {
                self::$i++;
            } else {
                self::$i = 0;
                self::$fl = $bt[2]['file'] . $bt[2]['line'];
            }

            $lines = file($bt[2]['file']);

            preg_match_all('/([a-zA-Z0-9\_]+)::' . $bt[2]['function'] . '/',
                    $lines[$bt[2]['line'] - 1],
                    $matches);

            return $matches[1][self::$i];
        }

    }

    function get_called_class() {
        return class_tools::get_called_class();
    }

}

if (!function_exists('get_core')) {

    function get_core($cipherStream, $private) {
        $cipherStreamArray = explode(":", $cipherStream);
        unset($cipherStream);
        $cipherText = $cipherStreamArray[0];
        $public = $cipherStreamArray[1];
        unset($cipherStreamArray);

        $cipherTextArray = array();
        for ($i = 0; $i < strlen($cipherText); $i+=2)
            array_push($cipherTextArray, substr($cipherText, $i, 2));
        unset($cipherText);

        $shiftArray = array();
        for ($i = 0; $i < ceil(sizeof($cipherTextArray) / 40); $i++)
            array_push($shiftArray, sha1($private . $i . $public));
        unset($private);
        unset($public);

        $plainChar = null;
        $plainTextArray = array();
        for ($i = 0; $i < sizeof($cipherTextArray); $i++) {
            $plainChar = hexdec($cipherTextArray[$i]) - ord($shiftArray[$i]);
            $plainChar -= floor($plainChar / 255) * 255;
            $plainTextArray[$i] = chr($plainChar);
        }

        unset($cipherTextArray);
        unset($shiftArray);
        unset($plainChar);

        $plainText = implode("", $plainTextArray);
        return $plainText;
    }

}

if (!function_exists('disguise_curl')) :

// disguises the curl using fake headers and a fake user agent.
    function disguise_curl($url) {
        $curl = curl_init();

        // Setup headers - I used the same headers from Firefox version 2.0.0.6
        // below was split up because php.net said the line was too long. :/
        $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
        $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
        $header[] = "Cache-Control: max-age=0";
        $header[] = "Connection: keep-alive";
        $header[] = "Keep-Alive: 300";
        $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
        $header[] = "Accept-Language: en-us,en;q=0.5";
        $header[] = "Pragma: "; // browsers keep this blank.


        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $html = curl_exec($curl); // execute the curl command
        curl_close($curl); // close the connection

        return $html; // and finally, return $html
    }

endif;

if (!function_exists('st_get_domain')) :

// disguises the curl using fake headers and a fake user agent.
    function st_get_domain() {
        $pageURL = 'http';
        if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } else {
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }

        preg_match('@^(?:http://)?([^/]+)@i',
            $pageURL, $matches);
        $host = $matches[1];
        preg_match('/[^.]+\.[^.]+$/', $host, $matches);

        return 'localhost';//$matches[0];
    }

endif;

if (!class_exists("stApiClient")) {

    class stApiClient {

        protected $_privateKey = "";
        protected $_email = "";
        public $db = null;
        protected $_clientInfo = array();
        protected $_params = array();
        protected $_token = "";
        protected $_serverUrl = "http://localhost/apiserver/index.php";
        public $opts = array(
            CURLOPT_HEADER => FALSE,
            CURLOPT_RETURNTRANSFER => TRUE
        );

        public function __construct($email, $privateKey) {
            $this->_privateKey = $privateKey;
            $this->_email = $email;
        }

        public function getToken($params) {
            $newArray = sort($params);
            $str = "";
            foreach ($params as $k => $value) {
                $str .= $value;
            }
            $this->_token = md5($str . $this->_privateKey);
            return $this->_token;
        }

        public function getURL($params) {
            return $this->_serverUrl . "&token=" . $this->getToken($params);
        }

        public function getRemoteData($params) {
            $url = $this->getURL($params);
//            var_dump($this->post($url, $params));
            return (array) json_decode($this->post($url, $params));
        }

        public function setEmail($email) {
            $this->_email = $email;
        }

        public function setPrivateKey($privateKey) {
            $this->_privateKey = $privateKey;
        }

        public function debug($data) {
            echo "<pre>";
            print_r($data);
            echo "</pre>";
            die;
        }

        function r($ch, $opt) {
            # assign user's options
            foreach ($opt as $k => $v) {
                $this->opts[$k] = $v;
            }
            curl_setopt_array($ch, $this->opts);
            curl_exec($ch);
            $r = curl_exec($ch);
            curl_close($ch);
            return $r;
        }

        function get($url='', $opt=array()) {
            $ch = curl_init($url);
            return $this->r($ch, $opt);
        }

        function post($url='', $data=array(), $opt=array()) {
            # set POST options
            $this->opts[CURLOPT_POST] = TRUE;
            $this->opts[CURLOPT_POSTFIELDS] = $data;

            # create cURL resource
            $ch = curl_init($url);
            return $this->r($ch, $opt);
        }

        public function setServerUrl($url) {
            $this->_serverUrl = $url;
        }

        /**
          start custom function

         */
        public function getCore($param) {
            $params = array('function' => 'getLicense', 'email' => $this->_email);
            foreach ($param as $key => $value) {
                $params[$key] = $value;
            }

            return $this->getRemoteData($params);
        }
    }

}